package es.onlysolutions.gs.web.controller;

import es.onlysolutions.arq.core.mvc.command.AbstractCommandBean;
import es.onlysolutions.arq.core.auth.IUserSettings;
import es.onlysolutions.gs.web.commandBean.LoginBean;
import es.onlysolutions.gs.comm.facade.UserFacade;
import es.onlysolutions.gs.comm.entity.User;
import es.onlysolutions.gs.comm.utils.UserSettings;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;

/**
 * Controller to login into the app.
 */
public class LoginController extends GSController
{

    private UserFacade userFacade;

    public void setUserFacade(UserFacade userFacade)
    {
        this.userFacade = userFacade;
    }

    protected AbstractCommandBean loadPage(HttpServletRequest httpServletRequest) throws Exception
    {
        LoginBean bean = new LoginBean();
        String url = ServletRequestUtils.getStringParameter(httpServletRequest, "url", "");
        if (url != null && url.length() > 0)
        {
            bean.setUrl(url);
        }
        return bean;

    }

    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception
    {
        LoginBean bean = (LoginBean) command;

        User user = userFacade.getUserByLogin( bean.getLogin() );

        UserSettings userSettings = new UserSettings();
        userSettings.setUser( user );

        HttpSession session = httpServletRequest.getSession(true);
        session.setAttribute(IUserSettings.USER_SETTINGS_ATTRIBUTE_NAME, userSettings);

        ModelAndView result;
        if (bean.getUrl() != null && bean.getUrl().length() > 0)
        {
            String withoutInitialSlash = bean.getUrl().substring(1);
            int indexOfEndAppName = withoutInitialSlash.indexOf('/');
            String urlWithoutAppName = withoutInitialSlash.substring(indexOfEndAppName);
            result = new ModelAndView("redirect:" + urlWithoutAppName);
        }
        else
        {
            result = new ModelAndView( getSuccessView(), getCommandName(), bean );
        }

        return result;
    }
}
